import axios, { AxiosError } from 'axios'
import type { ApiResponse } from '@/types/common'
import { getToken, removeToken } from '@/utils/auth'
import { ElMessage } from 'element-plus'

// 创建 axios 实例
const apiClient = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL,
  timeout: 10000,
})

// 请求拦截器：添加 token
apiClient.interceptors.request.use(
  (config) => {
    const token = getToken()
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器：处理 401
apiClient.interceptors.response.use(
  (response) => {
    return response
  },
  (error: AxiosError<ApiResponse<any>>) => {
    if (error.response?.status === 401) {
      // 清除 token
      removeToken()

      // 提示用户
      ElMessage.error('登录已过期，请重新登录')

      // 跳转到登录页
      window.location.href = '/login'
    }

    return Promise.reject(error)
  }
)

export default apiClient
